<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2018/8/28
 * Time: 11:10
 */

namespace app\api\controller;

use think\Db;

class Ali extends Base
{
    protected $config = array(
        'partner' => '2088621781822784',//用不着
        'seller_id' => 'admin@bagepanzi.com',//用不着
        'sign_type' => 'RSA2',// 直接写死了
        'it_b_pay' => '10m',//用不着
        'md5' => 'djqm7budkdlki6a76yasuyb9s1riiu1j',//用不着
        //支付公钥
        'ali_public' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvtxKiQmWumRieyB9HQnLcbNGeIbispUVqne70moTpKYg1ulBTN7Z0m2DvsoSCueujszNJwpPB3xuVdHDck3lAfY0BQM6mQHte3kZURhtE8f+DEEgp0+GSjur/b6lilF7D9Sv0qLvpIovRIMEFjN5caQw+LrsaSbTjasaWI8ZibcXfVnSVS29rLVprm0ZXXTxNYfEBVu2PjEZHMqRzCNiztKnglDeLpy2oeeiPGK4y+dd7I4ZS10V+rxaDMFe/ufEjpB5RdshaEj9hGmo4ChpqOVmR7qfjOFm/i3A52UggNVWnu5yWIEUGxYEDja2wSHw/vEeIO+MoNE5aR0NcAWo4wIDAQAB',
        //应用公钥
        'public_key' => "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsFZM2Zq4ac6t33JOfO7W9G2o+Bm+vMg6xLd3A4jLQ9hGTYsWXRlTmvL5pRztCJP4CcIA1DG2fm3K6vCxnYegBmvTD+2Ivqj0P5AJzy2i0+64X1AK6dkVtCorQLpald2mqRtocF9wk6hswWWA30tATB+BKsJsDN7aW9Sv3PyG8vn+M/UqTvnbH/RXKK5nHjXk9JmIVnSmMCWSKWde04QTXdc+1yDtVlCIDRxNZ+RCjNZ9C4xdlwZM/nf5brXON98QJNB4JxavodIQMGNQ3yclaY/pTwCkU2ncO01yPuin4oJgXBfQEGX0rWQEEp1jC8ZeQ4R1cf2N5WvZ5IhwHHfvyQIDAQAB",
        //应用私钥
        'private_key' => 'M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oGBAIFkR0Nqk5GFSjbpz++tQN3W/b6BAfMhh9HaX0k3ujrAqRm3Tezh7XC3JZmMzq4FDITE1pXIH6BsqYkJ3W6g55AysysMwZxOe5QckkNjf5qqYACnqjCqw8pIrnLK9pdgt602uCQ5508JLLhFlS5vPAjjWNXj+XtFTPS7P7vSH+tZAoGAP8/9I+fBklVJwOIWGbTtYks1RhP59OvIF2xq4zSVB8gDavW3FCCw9WPDN9d15Ew4zSgNZKrs75r0qtnXnxtqirPwSAnimM4sf+JHNIJLbqlObFC6oi2ztH/Rqx1H2umXG5edrmUxEwykFJBAKt5AebkAZutfwsttqTvCu1JJLtkCgYBZvx267rXuKJIiAijsX+Q4LPt5qq7bDSk6oeJ22aHb9UUlYwuVVUOw/qjdNGfUno3nHsiaaTtSA7l/H9IsLX1+cRX4oD+N1KIqQK68QSk0svCp6LPHj0zxyKl0zSJNbe1acWZGHmjiCYoa4xdUvW+bTUhnh5w2uJYJo81bJG0R9g=='
    );
    public $body;//描述
    public $subject;//描述
    public $total_amount;//金额
    public $out_trade_no;//订单号

    /**
     * @param $no
     * @param $money
     * @return string
     * 支付宝支付
     */
    public function getParam($no, $money, $body, $subject)
    {
//    public function getParam(){
        import('alipay.aop.AopClient', EXTEND_PATH);
        import('alipay.aop.request.AlipayTradeAppPayRequest', EXTEND_PATH);
//        $no = '5851546514677777712121212';
//        $no = time().rand(1000000,9999999);
        try {
            $aop = new \AopClient;
            $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do?charset=utf-8";
            $aop->appId = "2021001181697251";
            $aop->rsaPrivateKey = $this->config['private_key'];
            $aop->format = "json";
            $aop->charset = "UTF-8";
            $aop->signType = "RSA2";
            $aop->alipayrsaPublicKey = $this->config['public_key'];
            $request = new \AlipayTradeAppPayRequest();
            $bizcontent = "{\"body\":\"" . $body . "\","
                . "\"subject\": \"" . $subject . "\","
                . "\"out_trade_no\": \"" . $no . "\","
                . "\"timeout_express\": \"30m\","
                . "\"total_amount\": \"" . $money . "\","
                . "\"product_code\":\"QUICK_MSECURITY_PAY\""
                . "}";
            $request->setNotifyUrl("http://quan.xuanwumobile.com/api/Ali/huidiao");
            $request->setBizContent($bizcontent);
            $response = $aop->sdkExecute($request);
//            return $response;
            $res['msg'] = $response;
            $res['status'] = 200;
            return $res;
//            return json_encode($res);
        } catch(\Exception $e) {
            $res['msg'] = 'error';
            $res['status'] = 0;
            return $res;
        }
    }

    /**
     * 验证返回
     * @return bool
     */
    public function checkReturn()
    {
        import('alipay.aop.AopClient', EXTEND_PATH);
        $aop = new \AopClient;
        $aop->alipayrsaPublicKey = $this->config['ali_public'];
        $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");
        if($flag) {
            return $_POST;
        } else {
            return false;
        }
    }
    /***
     * @param $code
     * @param string $msg
     * 错误返回信息
     */
    protected function apiError($code, $msg = '')
    {
        if (!$msg) {
            $info['msg'] = $this->_error[$code]['msg'];
        } else {
            $info['msg'] = $msg;
        }
        $info['status'] = $code;
        $returnInfo = json_encode($info, JSON_UNESCAPED_UNICODE);
        echo $returnInfo;
        exit();
    }
    /**
     * 生成订单
     * @return string|void
     * user_id：用户ID,
     * type：1 课程购买  2 捐赠  3 打赏
     * price：打赏或捐赠的价格，当type为2或者3时传
     * activity_id：捐赠的活动ID，当type为2时，传此值
     */
    public function alipay()
    {
        extract(input());
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return $this->apiError(301);
        }
            if($params['type']==1){
                $money = input('param.money');//价格
                $money=0.01;
                $order_number = date('YmdHis') . str_pad(mt_rand(1, 9999), 6, '0', STR_PAD_LEFT).$user_id;
                $this->body = '小圈充值';
                $this->subject = '小圈会员充值';
                $this->total_amount = $money;
                $this->out_trade_no = $order_number;
                //插入订单表
                $data['order_number'] = $order_number;
                $data['order_userid'] = $user_id;
                $data['order_user_pay'] = $money;
                $data['order_type'] = 1;
                $data['order_time'] = date('Y-m-d H:i:s');
                $data['order_paytime'] = date('Y-m-d H:i:s');
                $res = Db::table('up_order')->insert($data);
                if($res) {
                    $respont = $this->getParam($this->out_trade_no, $this->total_amount, $this->body, $this->subject);
                    return json_encode($respont);
                } else {
                    return json_encode(['status' => 0, 'msg' => '生成订单失败，请联系管理员']);
                }
            }elseif ($params['type']==2){
                $money = input('param.money');//价格
                $recharge_gold = input('param.recharge_gold');//价格
                $money=0.01;
                $order_number = date('YmdHis') . str_pad(mt_rand(1, 999999), 6, '0', STR_PAD_LEFT).$user_id;
                $this->body = '小圈充值';
                $this->subject = '小圈充值';
                $this->total_amount = $money;
                $this->out_trade_no = $order_number;
                //插入订单表
                $data['recharge_num'] = $order_number;
                $data['recharge_user_id'] = $user_id;
                $data['recharge_money'] = $money;
                $data['recharge_gold'] = $recharge_gold;
                $data['recharge_type'] = 1;
                $data['recharge_time'] = date('Y-m-d H:i:s');
                $res = Db::table('up_recharge')->insert($data);
                if($res) {
                    $respont = $this->getParam($this->out_trade_no, $this->total_amount, $this->body, $this->subject);
                    return json_encode($respont);
                } else {
                    return json_encode(['status' => 0, 'msg' => '生成订单失败，请联系管理员']);
                }
            }

    }

    /**
     * 回调
     * @return string
     */
    public function write_admin_log($data)
    {
        $file_name = 'file/log/' . date('Ymd', time()) . '.txt';
        if (is_array($data)) {
            $data_str = implode(' | ', $data);
        } else {
            $data_str = $data;
        }
        file_put_contents($file_name, $data_str . "\r\n\r\n", FILE_APPEND);
    }

    public function huidiao()
    {
        $getInfo = $this->checkReturn();
        $rr['aa'] = json_encode($getInfo);
        if($getInfo) {
            if($getInfo['trade_status'] == 'TRADE_SUCCESS' || $getInfo['trade_status'] == 'TRADE_FINISHED') {
                $num = $getInfo['out_trade_no'];//订单号
                $dataOrder = array();
                $dataOrder['order_paytime'] = $getInfo['gmt_payment'];//支付时间
                Db::startTrans();
                try{
                    $info = Db::table('up_order')->where('order_number',$num)->find();
                    $info1 = Db::table('up_recharge')->where('recharge_num',$num)->find();
                    if($info['order_id']!=''){//会员充值
                        if($info['order_status'] == 1){
                            $dataOrder['order_status'] = 2;//1是未支付  2已支付
                            //更新订单状态
                            Db::table('up_order')->where('order_number',$num)->update($dataOrder);
                            //查询这个订单数据
                            //当前时间
                            Db::table('up_u_user')
                                ->where('user_id',$info['order_userid'])
                                ->setField('user_status',2);
                        }
                    }

                    if($info1['recharge_status']==1){//余额充值
                        $result['recharge_status'] = 2;
//                        $result['order_paytime'] = $getInfo['gmt_payment'];
                        Db::table('up_recharge')->where('recharge_num',$num)->update($result);
                        Db::table('up_u_user')->where('user_id',$info1['recharge_user_id'])->setInc('user_balance',$info1['recharge_gold']);
                    }

                    Db::commit();
                    die('success');
                }catch (\Exception $e) {
                    Db::rollback();
                    return 'error';
                }
            }
        }
    }
}